<?php

namespace app\controller;

use app\BaseController;
use think\App;
use think\facade\Cache;
use think\facade\View;
use think\facade\Db as db;
use think\Model;
use think\Request;
use app\utils\simple_html_dom;
use Xhat\Payjs\Payjs;


class Pay extends BaseController
{

    var $config = [
        'mchid' => '1617634538',   // 配置商户号
        'key'   => 'dVpCWyd35rmY9VPz',   // 配置通信密钥
    ];

    var $payjs;

    public function __construct(App $app)
    {
        parent::__construct($app);

        // 配置通信参数
        $this->payjs = new Payjs($this->config);

    }

    public function test()
    {

        $total_fee = $this->request->param('fee',2);

        // 构造订单基础信息
        $data = [
            'body' => 'Hello订单测试',                        // 订单标题
            'total_fee' => $total_fee,                           // 订单金额
            'out_trade_no' => time(),                   // 订单号
            'attach' => '星云课堂',            // 订单附加信息(可选参数)
            'notify_url' => 'http://ke.itsub.cn/payjs/notify',    // 异步通知地址(可选参数)
        ];

        $result = $this->payjs->native($data);
        print_r($result);
        View::assign('data', $result);

        //$sql = "select *,b.type v_type from lesson a left join video b on a.video_id=b.id where a.id=:lid";

        return \view('/pay/index');

    }


    public function notify()
    {


        $data = $_POST;

        if($data['return_code'] == 1){
            // 1.验签逻辑
            $sign = $data['sign'];
            // 2.验重逻辑

            // 3.自身业务逻辑

            // 4.返回 success 字符串（http状态码为200）
            $result = $this->payjs->sign($data);
            $content = json_encode($result,JSON_UNESCAPED_UNICODE).$sign;
            DB::table('logs')->insert(['content'=>$content]);
            echo 'success';
        }

        // 根据订单号查询订单状态


        //echo $result;
        /*return json_encode([
            'code'=>0,
            'msg'=>'ok',
            'status'=>$result['status'],
            'total_fee'=>$result['total_fee'],
        ],JSON_UNESCAPED_UNICODE);*/
    }


    public function payjs_order_check()
    {

        $payjs_order_id = $this->request->param('payjs_order_id');

        // 根据订单号查询订单状态
        $result = $this->payjs->check($payjs_order_id);
        print_r($result);
        //echo $result['status'];
        return json_encode([
            'code'=>0,
            'msg'=>'ok',
            'status'=>$result['status'],
            'total_fee'=>$result['total_fee'],
        ],JSON_UNESCAPED_UNICODE);
    }


}
